package com.wlyy.bcwlw.base;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.alibaba.fastjson.JSON;
import com.rework.joss.persistence.convention.utils.ConventionUtils;
import com.wlyy.bcwlw.common.exception.WebException;
import com.wlyy.bcwlw.common.export2excel.WebExport2ExcelHandler;
import com.wlyy.bcwlw.common.export2excel.entity.Export2ExcelRow;
import com.wlyy.bcwlw.common.export2excel.service.Export2ExcelConverterForRow;
import com.wlyy.bcwlw.common.grid.GridUtils;
/** 
 * <p>Description: TODO</p>
 * @author zhangyang
 * <p>日期:2015年6月11日 上午9:27:03</p> 
 * @version V1.0 
 */
public class BaseController {

	
	public static final int DEFAULT_PAGE_SIZE = 10;

	public static final String ENCODE = "utf-8";
	
	public static final String SUCCESS_MESSAGE = "successMessage";
	
	public static final String ERROR_MESSAGE = "errors";
	
	
	
	
	protected int getInt(HttpServletRequest request, String param, int defaultValue) {
		String value = request.getParameter(param);
		return NumberUtils.isNumber(value) ? Integer.parseInt(value) : defaultValue;
	}
	
	protected Integer getInteger(HttpServletRequest request, String param) {
		String value = request.getParameter(param);
		return NumberUtils.isNumber(value) ? Integer.parseInt(value) : null;
	}
	
	protected Long getLong(HttpServletRequest request, String param) {
		String value = request.getParameter(param);
		return NumberUtils.isNumber(value) ? Long.parseLong(value) : null;
	}
	
	protected String get(HttpServletRequest request, String param) {
		String value = request.getParameter(param);
		return value != null&&!"null".equals(value) ? value.trim() : null;
	}
	
	protected String get(HttpServletRequest request, String param, String defaultValue) {
		String value = request.getParameter(param);
		return StringUtils.isNotBlank(value)? value.trim() : defaultValue;
	}
	
	protected String[] getValues(HttpServletRequest request, String param) {
		String[] values = request.getParameterValues(param);
		return values == null ? new String[0] : values;
	}
	
	/**
	 * 设置成功信息
	 * 
	 * @param request
	 * @param successMessages
	 */
	protected void setSuccessMessage(HttpServletRequest request,
			List<String> successMessages) {
		request.setAttribute(SUCCESS_MESSAGE, successMessages);
	}
	/**
	 * 设置成功信息
	 */
	protected void setSuccessMessage(HttpServletRequest request,
			String successMessage) {
		setSuccessMessage(request, ConventionUtils.toList(successMessage));
	}
	
	/**
	 * 增加成功信息
	 */
	protected void addSuccessMessage(HttpServletRequest request,
			String successMessage) {
		addContent2Request(request, successMessage, SUCCESS_MESSAGE);
	}

	/**
	 * 增加成功信息
	 */
	protected void addSuccessMessage(HttpServletRequest request,
			List<String> successMessages) {
		addList2Request(request, successMessages, SUCCESS_MESSAGE);
	}

	/**
	 * 设置失败信息
	 */
	protected void setErrorMessage(HttpServletRequest request, List<String> errors) {
		request.setAttribute(ERROR_MESSAGE, errors);
	}
	
	protected void setErrorMessage(HttpServletRequest request, String error) {
		setErrorMessage(request, ConventionUtils.toList(error));
	}
	
	private void addList2Request(HttpServletRequest request,
			List<String> contents, String requestName) {
		List<String> list = (List<String>) request.getAttribute(requestName);
		if (list == null) {
			list = new ArrayList<String>();
		}
		list.addAll(contents);
		request.setAttribute(requestName, list);
	}
	
	private void addContent2Request(HttpServletRequest request,
			String content, String requestName) {
		List<String> list = (List<String>) request.getAttribute(requestName);
		if (list == null) {
			list = new ArrayList<String>();
		}
		list.add(content);
		request.setAttribute(requestName, list);
	}
	
	protected void sendMessage(HttpServletResponse response, String str) throws Exception{
		response.setContentType("text/html; charset=" + ENCODE);
		PrintWriter writer = response.getWriter();
		writer.println(str);
		writer.close();
		response.flushBuffer();
	}
	protected void sendJsonMessage(HttpServletResponse response, Map str) throws Exception{
		response.setContentType("text/html; charset=" + ENCODE);
		PrintWriter writer = response.getWriter();
		writer.println("["+JSON.toJSON(str)+"]");
		writer.close();
		response.flushBuffer();
	}
	/**
	 * 将某个对象转换成json格式并发送到客户端
	 * @param response
	 * @param obj
	 * @throws Exception
	 */
	protected void sendJsonMessage(HttpServletResponse response,Object obj) throws Exception{
		response.setContentType("text/html; charset=" + ENCODE);
		PrintWriter writer = response.getWriter();
		writer.println(JSON.toJSON(obj));
		writer.close();
		response.flushBuffer();
	}
	
	protected String toJsonString(Object o) {
		return JSON.toJSON(o).toString();
	}
	
	protected void set(HttpServletRequest request, String paramName, Object value) {
		request.setAttribute(paramName, value);
	}
	
	/**
	 * 当前页码
	 * @param request
	 * @return
	 */
	protected int getPageNum(HttpServletRequest request) {
		return GridUtils.getPageNum(request);
	}
	
	
	/**
	 * 每页显示记录数
	 * @param request
	 * @return
	 */
	protected int getInternal(HttpServletRequest request) {
		return GridUtils.getInternal(request);
	}
	
	/**
	 * 当前排序字段
	 * @param request
	 * @return
	 */
	protected String getSortName(HttpServletRequest request){
		return GridUtils.getSortName(request);
	}
	
	/**
	 * 当前排序类型
	 * @param request
	 * @return
	 */
	protected String getSortOrder(HttpServletRequest request){
		return GridUtils.getSortOrder(request);
	}
	
	/**
	 * 每条记录起始位置
	* @param records
	* @param page
	* @param limit
	* @exception.
	 */
	protected int getRecordStart(int records, int page, int limit) {
		int totalPages = GridUtils.getTotalPages(records, limit);
		if (page > totalPages) {
			page = totalPages;
		}
		int start = (page - 1) * limit;
		//mysql中start不能为负
		if (start < 0) {
			start = 0;
		}
		return start;
	}
	
	protected void processJsonData4Grid(
			HttpServletRequest request, HttpServletResponse response, int limit, int page, int records, List rows) throws Exception {
		processJsonData4Grid(request,response, limit, page, records, rows, null);
	}
	
	private void processJsonData4Grid(
			HttpServletRequest request, HttpServletResponse response, int limit, int page, int records, List rows, Map userData) throws Exception {
		if ("excel".equals(get(request, "app_exportDataType"))) {
			String ids = get(request, "app_exportIds");
			if (StringUtils.isNotBlank(ids)) {
				List<Object> exportList = new ArrayList<Object>();
				List<String> idList = Arrays.asList(StringUtils.split(ids, ","));
				
				for (Object baseObject : rows) {
						String id = BeanUtils.getSimpleProperty(baseObject, "id");
						if (StringUtils.isNotBlank(id) && idList.contains(id)) {
							exportList.add(baseObject);
						}

				}
				rows = exportList;
				
			}
			
			doExportExcel(request, response, (BaseDTO[])rows.toArray(new BaseDTO[0])); 
			return;
		}
		if(userData == null){
			userData = new HashMap();
		}
		sendMessage(response, GridUtils.constructJsonData4Grid(limit, page, records, rows, userData));
	}
	
	protected void doExportExcel(HttpServletRequest request, HttpServletResponse response, BaseDTO[] dtos) throws Exception {
		
		String[] header = request.getParameterValues("app_exportHeaderName");
		String[] colNames = request.getParameterValues("app_exportColumnName");
    	
		doExportExcel(response, dtos, header, colNames);


	}

	protected void doExportExcel( HttpServletResponse response, BaseDTO[] dtos, String[] header, String[] colNames) throws Exception {
		
    	Export2ExcelRow[] rows = null;
    	try {
        	if (!ArrayUtils.isEmpty(dtos) && !ArrayUtils.isEmpty(colNames))
    			rows = Export2ExcelConverterForRow.convertToRow(colNames, dtos);
    		WebExport2ExcelHandler handler = new WebExport2ExcelHandler(header,rows);
    		handler.export2Excel(response);
    	} catch (Exception e) {
			throw new WebException("导出Excel出错！", e);
		}

	}



}
